<template>
  <div class="organization">
    <el-row :gutter="15">
      <el-col :span="6">
        <aside />
        <sticky :sticky-top="99">
          <div class="gl_contentBox gl_heightFull">
            <el-row class="gl_pb_10 gl_ft_weight">
              <!-- <el-col :span="20">{{ appTitle }}</el-col> -->
              <el-col v-if="canCreateRoot" :span="24" align="right">
                <!-- 如果树结构不存在会显示“新增组织”按钮，则不需要显示此按钮 -->
                <!-- <template v-if="firstLevelInfo.code !== ''">
                  <el-button type="primary" size="mini" @click="dropdownAddUnitDialog('addSibling', 'addTopLevel')">新增顶级单位</el-button>
                </template> -->
              </el-col>
            </el-row>
            <el-scrollbar v-loading="treeLoading" style="height: calc(100vh - 182px);">
              <template v-if="organizationUnitsTree.length > 0">
                <el-tree ref="viewTree" lazy :props="{isLeaf: '_ISLEAF'}" :load="loadTreeNode" :data="organizationUnitsTree" node-key="code" highlight-current :expand-on-click-node="false" empty-text="请先新增一个组织!" @node-click="handleNodeClick">
                  <span slot-scope="{ node, data }" class="custom-tree-node" :title="node.data.displayName">
                    <span class="gl_ellipsis" style="width: calc(100% - 30px);display: inline-block;">{{ node.data.displayName }}</span>
                    <span class="custom-tree-node-item">
                      <el-dropdown @command="dropdownAddUnitDialog">
                        <span class="el-dropdown-link">
                          <i class="el-icon-more" />
                        </span>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item v-if="!currentTreeIsClub" :command="{tree: data, node: node, type: 'add'}">新增下属部门</el-dropdown-item>
                          <!-- 无锡中心可以添加内部机构 -->
                          <template v-if="currentRootTypeCode === 'WXCenter' && (node.data.typeCode === 'WXCenter' || node.data.typeCode === 'CityTA' || node.data.typeCode === 'ProvinceTA')">
                            <el-dropdown-item :command="{tree: data, node: node, type: 'addInner'}">新增内部机构</el-dropdown-item>
                          </template>
                          <template v-if="!node.data.typeCode">
                            <el-dropdown-item :command="{tree: data, node: node, type: 'edit'}">{{ $t('button.edit') }}</el-dropdown-item>
                          </template>
                          <template v-if="node.data.typeCode">
                            <el-dropdown-item :command="{tree: data, node: node, type: 'editInner'}">{{ $t('button.edit') }}</el-dropdown-item>
                          </template>
                          <!-- 内部机构(typeCode === 'TA' || typeCode === 'ProvinceTA' || typeCode === 'Club')上面加个禁用和转移两个功能 -->
                          <!-- TA（协会）分为CityTA、CountyTA -->
                          <div v-if="!currentTreeIsClub">
                            <template v-if="node.data.typeCode === 'CityTA' || node.data.typeCode === 'ProvinceTA' || node.data.typeCode === 'CountyTA' || node.data.typeCode === 'Club'">
                              <template v-if="data.code !== firstLevelInfo.code">
                                <el-dropdown-item v-if="!node.data.isEnabled" :command="{tree: data, node: node, type: 'enabled'}">启用</el-dropdown-item>
                                <el-dropdown-item v-else :command="{tree: data, node: node, type: 'disabled'}">禁用</el-dropdown-item>
                              </template>
                            </template>
                          </div>
                          <template v-if="currentRootTypeCode === 'WXCenter' || currentRootTypeCode === 'ProvinceTA' || currentRootTypeCode === 'CityTA' || currentRootTypeCode === 'CountyTA'">
                            <el-dropdown-item v-if="node.data.typeCode === 'Club'" :command="{tree: data, node: node, type: 'transfer'}">转移</el-dropdown-item>
                          </template>
                          <!-- <template v-if="currentRootTypeCode === 'WXCenter' || currentRootTypeCode === 'ProvinceTA' || currentRootTypeCode === 'CityTA' || currentRootTypeCode === 'CountyTA'"> -->
                          <template v-if="currentRootTypeCode === 'WXCenter'">
                            <el-dropdown-item v-if="node.data.typeCode === 'Club'" :command="{tree: data, node: node, type: 'addgym'}">分配系统</el-dropdown-item>
                          </template>
                          <template v-if="data.code !== firstLevelInfo.code">
                            <el-dropdown-item :command="{node: node, tree: data, type: 'delete'}">{{ $t('button.delete') }}</el-dropdown-item>
                          </template>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </span>
                  </span>
                </el-tree>
              </template>
              <template v-if="organizationUnitsTree.length === 0">
                <div class="tree_nodata">暂无数据</div>
              </template>
              <!-- <div v-else-if="firstLevelInfo.code === ''" align="center" class="gl_pt_20">
                <el-button type="success" size="large" @click="dropdownAddUnitDialog('addSibling', 'addOrg')">新增组织</el-button>
              </div> -->
            </el-scrollbar>
          </div>
        </sticky>
      </el-col>
      <el-col :span="18">
        <div class="gl_contentBox gl_heightFull" v-loading="treeLoading">
          <el-row :gutter="20" class="gl_pb_10">
            <template v-if="firstLevelInfo.code !== ''">
              <el-col :span="24">
                当前选定单位：
                <span v-if="parentAddUnitInfo.id&&!currentTreeIsClub">{{ parentAddUnitInfo.displayName ? parentAddUnitInfo.displayName + ' -' : '' }}</span>
                <span v-if="currentTreeData.id">{{ currentTreeData ? currentTreeData.displayName : '' }}</span>
                <!-- <span v-if="!currentTreeIsClub">
                  <el-button v-if="userInfo.isSuperAdmin" style="margin-left:27px" :loading="buLoading" type="primary" size="mini" @click="reportData()">数据导出</el-button>
                </span> -->
              </el-col>
            </template>
          </el-row>
          <!-- 头部按钮 -->
          <div v-if="TAManagement && department " style="margin-bottom:9px">
            <div class="headerTop">
              <div v-if="!currentTreeIsClub">
                <img class="img" :src="getStaticFileUrl(logo)" alt="">
              </div>
              <div v-if="!currentTreeIsClub">
                <div>
                  <el-button type="primary" size="mini" @click="toRegisterPersonal()">注册人员列表</el-button>
                  <el-button type="primary" size="mini" @click="enrollorganization()">注册机构列表</el-button>
                  <el-button v-if="game" type="primary" size="mini" @click="goGame()">赛事</el-button>
                  <el-button v-if="tran" type="primary" size="mini" @click="goTran()">培训</el-button>
                  <el-button v-if="mall" type="primary" size="mini" @click="goMall()">商城</el-button>
                  <el-button v-if="duan" type="primary" size="mini" @click="toDanGrade()">级段位申报</el-button>
                  <el-button v-if="duan" type="primary" size="mini" @click="toMemberDues()">会员费</el-button>
                  <el-button type="primary" size="mini" @click="toOrganData()">数据</el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧面板内容 -->
          <template v-if="!currentTreeIsClub">

            <el-tabs v-if="TAManagement" v-model="activeName" class="gl_tabs" type="card">
              <el-tab-pane label="内部成员" name="0">
                <div class="demo-input-suffix gl_searchBox">
                  <el-row :gutter="20">
                    <el-col :span="5">
                      <p>{{ $t('search.state') }} </p>
                      <el-select v-model="orgPageListQO.IsEnabled" size="mini" clearable filterable placeholder="请选择状态" @change="getPageData()">
                        <el-option :value="true" :label="$t('table.enable')" />
                        <el-option :value="false" :label="$t('table.disable')" />
                      </el-select>
                    </el-col>
                    <el-col :span="5">
                      <p>姓名/手机</p>
                      <el-input v-model="orgPageListQO.Filter" clearable placeholder="请输入用户名、手机号查询" size="mini" @change="getPageData()" />
                    </el-col>
                    <el-col :span="12">
                      <el-button style="margin-top:27px" type="primary" size="mini" @click="getPageData()">{{ $t('button.query') }}</el-button>
                      <el-button style="margin-top:27px" type="warning" size="mini" @click="handleRefreshData">{{ $t('button.Reset') }}</el-button>
                    </el-col>
                  </el-row>
                </div>
                <el-row v-if="organizationUnitsTree.length > 0" :gutter="20" class="gl_my_15">
                  <el-col :md="6" :lg="4">
                    <el-button type="success" size="mini" @click="handleOperateUserRow('add')">新增人员</el-button>
                  </el-col>
                </el-row>
                <el-row v-else class="gl_mt_15" />
                <el-table v-loading="loading" :data="tableData" size="mini" :row-class-name="tableRowClassName" stripe>
                  <el-table-column prop="name" label="姓名" width="180" />
                  <el-table-column prop="phoneNumber" label="手机号码" align="center" width="120" />
                  <el-table-column :label="$t('table.status')" align="center" width="100">
                    <template slot-scope="{row}">
                      <span :class="row.isEnabled ? 'gl_color_success' : 'gl_color_error'">
                        <i :class="row.isEnabled ? 'el-icon-success' : 'el-icon-error'" />
                        <span class="gl_pl_5">{{ row.isEnabled ? '正常' : $t('table.disable') }}</span>
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column label="所属机构" align="left" width="200">
                    <template slot-scope="{ row }">
                      {{ row.organizationUnit ? row.organizationUnit.displayName : '' }}
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('table.description')" min-width="240">
                    <template slot-scope="{row}">
                      <el-popover placement="top-start" width="500" trigger="hover" :content="row.description">
                        <span slot="reference" class="gl_ellipsis">{{ row.description }}</span>
                      </el-popover>
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('table.actions')" width="200">
                    <template slot-scope="scope">
                      <el-button type="text" size="mini" @click="handleOperateUserRow('edit', scope.row)">{{ $t('button.edit') }}</el-button>
                      <el-button type="text" size="mini" @click="handleTransfer(scope.row)">转组</el-button>
                      <template v-if="!(userInfo.id === scope.row.id || scope.row.isSuperAdmin)">
                        <el-button type="text" size="mini" @click="handleForbidden(scope.row)"><span class="gl_color_warning">{{ scope.row.isEnabled ? $t('table.disable') : $t('table.enable') }}</span></el-button>
                      </template>
                      <template v-if="!(userInfo.id === scope.row.id || scope.row.isSuperAdmin)">
                        <el-button type="text" size="mini" @click="handleDeleteUser(scope.row)">
                          <span class="gl_color_error">删除</span>
                        </el-button>
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
                <div align="center" class="gl_py_10">
                  <el-pagination :current-page="orgPageListQO.Page" :page-size="orgPageListQO.maxResultCount" :total="totalPage" layout="total,sizes,prev,pager,next,jumper" :page-sizes="[10, 20, 30, 40]" @size-change="sizeChange" @current-change="pageIndexChange" />
                </div>
              </el-tab-pane>
              <el-tab-pane v-if="TAManagement && department" label="团体成员" name="1">
                <Teampeople ref="teampeople" />
              </el-tab-pane>
            </el-tabs>
            <div v-else>
              <div class="demo-input-suffix gl_searchBox">
                <el-row :gutter="20">
                  <el-col :span="5">
                    <p>{{ $t('search.state') }} </p>
                    <el-select v-model="orgPageListQO.IsEnabled" size="mini" clearable filterable placeholder="请选择状态" @change="getPageData()">
                      <el-option :value="true" :label="$t('table.enable')" />
                      <el-option :value="false" :label="$t('table.disable')" />
                    </el-select>
                  </el-col>
                  <el-col :span="5">
                    <p>姓名/手机</p>
                    <el-input v-model="orgPageListQO.Filter" clearable placeholder="请输入用户名、手机号查询" size="mini" @change="getPageData()" />
                  </el-col>
                  <el-col :span="12">
                    <el-button style="margin-top:27px" type="primary" size="mini" @click="getPageData()">{{ $t('button.query') }}</el-button>
                    <el-button style="margin-top:27px" type="warning" size="mini" @click="handleRefreshData">{{ $t('button.Reset') }}</el-button>
                  </el-col>
                </el-row>
              </div>
              <el-row v-if="organizationUnitsTree.length > 0" :gutter="20" class="gl_my_15">
                <el-col :md="6" :lg="4">
                  <el-button type="success" size="mini" @click="handleOperateUserRow('add')">新增人员</el-button>
                </el-col>
              </el-row>
              <el-row v-else class="gl_mt_15" />
              <el-table v-loading="loading" :data="tableData" size="mini" :row-class-name="tableRowClassName" stripe>
                <el-table-column prop="name" label="姓名" width="180" />
                <el-table-column prop="phoneNumber" label="手机号码" align="center" width="120" />
                <el-table-column :label="$t('table.status')" align="center" width="100">
                  <template slot-scope="{row}">
                    <span :class="row.isEnabled ? 'gl_color_success' : 'gl_color_error'">
                      <i :class="row.isEnabled ? 'el-icon-success' : 'el-icon-error'" />
                      <span class="gl_pl_5">{{ row.isEnabled ? '正常' : $t('table.disable') }}</span>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="所属机构" align="left" width="200">
                  <template slot-scope="{ row }">
                    {{ row.organizationUnit ? row.organizationUnit.displayName : '' }}
                  </template>
                </el-table-column>
                <el-table-column :label="$t('table.description')" min-width="240">
                  <template slot-scope="{row}">
                    <el-popover placement="top-start" width="500" trigger="hover" :content="row.description">
                      <span slot="reference" class="gl_ellipsis">{{ row.description }}</span>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('table.actions')" width="200">
                  <template slot-scope="scope">
                    <el-button type="text" size="mini" @click="handleOperateUserRow('edit', scope.row)">{{ $t('button.edit') }}</el-button>
                    <el-button type="text" size="mini" @click="handleTransfer(scope.row)">转组</el-button>
                    <template v-if="!(userInfo.id === scope.row.id || scope.row.isSuperAdmin)">
                      <el-button type="text" size="mini" @click="handleForbidden(scope.row)"><span class="gl_color_warning">{{ scope.row.isEnabled ? $t('table.disable') : $t('table.enable') }}</span></el-button>
                    </template>
                    <template v-if="!(userInfo.id === scope.row.id || scope.row.isSuperAdmin)">
                      <el-button type="text" size="mini" @click="handleDeleteUser(scope.row)">
                        <span class="gl_color_error">删除</span>
                      </el-button>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
              <div align="center" class="gl_py_10">
                <el-pagination :current-page="orgPageListQO.Page" :page-size="orgPageListQO.maxResultCount" :total="totalPage" layout="total,sizes,prev,pager,next,jumper" :page-sizes="[10, 20, 30, 40]" @size-change="sizeChange" @current-change="pageIndexChange" />
              </div>
            </div>

          </template>
          <template v-if="currentTreeIsClub">
            <div>
              <ClubBaseInfo ref="refClubBaseInfo" :info="currentTreeData" />
            </div>
          </template>
        </div>
      </el-col>
    </el-row>
    <!-- 新增/修改下属部门 -->
    <el-dialog :title="dialogAddUnitInfo.displayName" width="560px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogOperateUnit">
      <el-form ref="refFormAddUnit" label-width="120px" :model="organizationUnitCreateInput" :rules="formOperateUnitVO_Rules" @submit.native.prevent>
        <template v-if="currentAddUnitData.code === firstLevelInfo.code && dialogOperateUnitType === 'edit'">
          <!-- 修改信息 - 修改第一级, 没有上级单位 -->
          <el-form-item label="当前单位/部门" prop="displayName" size="mini">
            <el-input v-model="organizationUnitCreateInput.displayName" clearable />
          </el-form-item>
        </template>
        <template v-else>
          <template v-if="dialogAddUnitInfo.code === 'addOrg'">
            <!-- 新增组织(第一级) -->
            <el-form-item label="当前单位/部门" prop="displayName" size="mini">
              <el-input v-model="organizationUnitCreateInput.displayName" clearable placeholder="请输入单位/部门名称" />
            </el-form-item>
          </template>
          <template v-else-if="dialogAddUnitInfo.code === 'addTopLevel'">
            <!-- 新增顶级单位 -->
            <el-form-item label="当前单位/部门" prop="displayName" size="mini">
              <el-input v-model="organizationUnitCreateInput.displayName" clearable placeholder="请输入单位/部门名称" />
            </el-form-item>
          </template>
          <template v-else>
            <!-- 顶级 -->
            <el-form-item v-if="currentAddUnitData.code.indexOf(firstLevelInfo.code) !== -1" label="上级单位/部门" size="mini">
              <span v-if="dialogAddUnitInfo.code === 'addSubBranch'">{{ currentAddUnitData.displayName }}</span>
              <span v-if="dialogAddUnitInfo.code === 'editInfo'">{{ parentAddUnitInfo.displayName }}</span>
            </el-form-item>
            <!-- 子级 -->
            <el-form-item v-else-if="parentAddUnitInfo.displayName" label="上级单位/部门" size="mini">
              <!-- addSubBranch: 新增下属部门; editInfo: 修改信息 -->
              <span v-if="dialogAddUnitInfo.code === 'addSubBranch'">{{ currentAddUnitData.displayName }}</span>
              <span v-if="dialogAddUnitInfo.code === 'editInfo'">{{ parentAddUnitInfo.displayName }}</span>
            </el-form-item>
            <el-form-item label="当前单位/部门" prop="displayName" size="mini">
              <el-input v-model="organizationUnitCreateInput.displayName" clearable placeholder="请输入单位/部门名称" />
            </el-form-item>
          </template>
        </template>
        <!-- 内部机构新增需要填写机构类型和地理范围 -->
        <template v-if="dialogOperateUnitType === 'addInner' || dialogOperateUnitType === 'editInner'">
          <!-- 机构类型 -->
          <el-form-item label="机构类型" prop="typeCode" size="mini" style="width: 100%;">
            <el-select v-if="dialogOperateUnitType === 'addInner'" v-model="organizationUnitCreateInput.typeCode" size="mini" placeholder="请选择机构类型">
              <template v-for="item in organizationUnitsTypes">
                <!-- 操作用户为无锡中心 -->
                <template v-if="currentRootTypeCode === 'WXCenter'">
                  <template v-if="dialogAddUnitInfo.typeCode === 'WXCenter'">
                    <el-option v-if="item.code !== 'WXCenter'" :key="item.code" :value="item.code" :label="item.name" />
                  </template>
                  <template v-if="dialogAddUnitInfo.typeCode === 'ProvinceTA'">
                    <el-option v-if="item.code === 'CityTA'" :key="item.code" :value="item.code" :label="item.name" />
                  </template>
                  <template v-if="dialogAddUnitInfo.typeCode === 'CityTA'">
                    <el-option v-if="item.code === 'CountyTA'" :key="item.code" :value="item.code" :label="item.name" />
                  </template>
                </template>
                <template v-else>
                  <el-option v-if="item.code === 'Club'" :key="item.code" :value="item.code" :label="item.name" />
                </template>
              </template>
            </el-select>
            <span v-else>{{ findDictDataByCode(currentAddUnitData.typeCode).name }}</span>
          </el-form-item>
          <el-alert v-if="dialogOperateUnitType === 'addInner'" style="margin-bottom: 24px;" title="注：请慎重选择机构类型，保存之后将不能修改" type="warning" />
          <!-- 地理范围 -->
          <el-row v-if="organizationUnitCreateInput.typeCode === 'ProvinceTA' || organizationUnitCreateInput.typeCode === 'CityTA' || organizationUnitCreateInput.typeCode === 'CountyTA'" :gutter="15">
            <el-col :span="12">
              <el-form-item label="地理范围" prop="provinceCode" size="mini">
                <el-select v-model="organizationUnitCreateInput.provinceCode" :disabled="currentRootTypeCode !== 'WXCenter'" size="mini" clearable placeholder="请选择省" @change="getCityList">
                  <el-option v-for="item in provinceList" :key="item.code" :value="item.code" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="" label-width="0" size="mini">
                <el-select v-model="organizationUnitCreateInput.cityCode" :disabled="currentRootTypeCode !== 'WXCenter'" size="mini" clearable placeholder="请选择市" @change="getCountryList">
                  <el-option v-for="item in cityList" :key="item.code" :value="item.code" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="" label-width="0" size="mini">
                <el-select v-model="organizationUnitCreateInput.countyCode" :disabled="currentRootTypeCode !== 'WXCenter'" size="mini" clearable placeholder="请选择区县">
                  <el-option v-for="item in countryList" :key="item.code" :value="item.code" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-alert type="warning">
              <div slot="title">注：地理范围表示管理的区域，选择对应的省、市、区将会影响管理的道馆（市、区非必选）</div>
            </el-alert>
          </el-row>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogOperateUnit = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="submitLoading" @click="dropdownSubmitUnit">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
    <!-- 新增用户 -->
    <el-dialog :title="dialogOperateUserType === 'add' ? '新增用户' : '修改用户'" width="880px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogOperateUser">
      <el-scrollbar v-loading="dialogLoading" wrap-class="scrollbar-wrapper gl_dialog_height">
        <el-form ref="refFormAddUser" label-width="120px" class="gl_px_10 gl_pb_15" :model="identityUserCreateDto" :rules="formOperateUserVo_Rules" @submit.native.prevent>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="当前所属单位" size="mini">
                <span>{{ parentAddUnitInfo.displayName ? parentAddUnitInfo.displayName + ' —' : '' }} {{ currentTreeData ? currentTreeData.displayName : '' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name" size="mini">
                <el-input v-model="identityUserCreateDto.name" clearable placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phoneNumber" size="mini">
                <el-input v-model="identityUserCreateDto.phoneNumber" clearable placeholder="请输入手机号码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('table.status')" prop="isEnabled" size="mini">
                <el-radio-group v-model="identityUserCreateDto.isEnabled">
                  <el-radio :label="true">{{ $t('table.enable') }}</el-radio>
                  <el-radio :label="false">{{ $t('table.disable') }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色权限" size="mini" prop="roleIds">
                <el-select v-model="identityUserCreateDto.roleIds" placeholder="请选择角色权限" style="width: 100%">
                  <el-option v-for="item in roleList" :key="item.id" :value="item.id" :label="item.displayName" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设置为初始密码">
                <el-switch v-model="isDefaultPwd" />
                <span>（设置初始密码为: Asd123）</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="登录密码" prop="password" size="mini">
                <template v-if="pwdIsDisabled">
                  <el-input v-model="identityUserCreateDto.password" :type="identityUserCreateDto.password === randomPwd ? 'password' : 'text'" disabled />
                </template>
                <template v-else>
                  <template v-if="dialogOperateUserType === 'edit'">
                    <el-input v-model="identityUserCreateDto.password" :type="'password'" clearable :show-password="identityUserCreateDto.password !== randomPwd" placeholder="请输入登录密码" />
                  </template>
                  <template v-if="dialogOperateUserType === 'add'">
                    <el-input v-model="identityUserCreateDto.password" :type="'password'" clearable show-password placeholder="请输入登录密码" />
                  </template>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('table.description')" size="mini">
                <el-input v-model="identityUserCreateDto.description" clearable type="textarea" show-word-limit maxlength="200" placeholder="请输入描述信息" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-scrollbar>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogOperateUser = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="submitLoading" @click="handleSubmitUser">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
    <!-- 转组 -->
    <el-dialog title="转组" width="440px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogTransfer">
      <el-form ref="refFormTransfer" label-width="130px" :model="formTransferVO" :rules="formTransferVO_Rules" @submit.native.prevent>
        <el-form-item label="当前单位/部门" size="mini">
          <span>{{ tableRow && tableRow.organizationUnit ? tableRow.organizationUnit.displayName : '' }}</span>
        </el-form-item>
        <el-form-item label="选择新单位/部门" prop="sector" size="mini">
          <el-cascader :key="cascaderKey" v-model="formTransferVO.sector" :options="optionsOrganizationUnits" :props="{ label: 'displayName', value: 'id' }" style="width: 90%;" clearable placeholder="请选择部门" />
          <!-- :props="{ checkStrictly: true }" 选择任意一级选项  -->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogTransfer = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="submitLoading" @click="handleSubmitUserTransfer">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
    <!-- 机构转组 -->
    <el-dialog title="转组" width="440px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogTransferOrganization">
      <el-form ref="organizationUnitMoveInput" label-width="130px" :model="organizationUnitMoveInput" :rules="organizationUnitMoveInput_Rules" @submit.native.prevent>
        <el-form-item label="当前机构" size="mini">
          <span>{{ parentAddUnitInfo.displayName }}</span>
        </el-form-item>
        <el-form-item label="选择新机构" prop="newParentId" size="mini">
          <el-cascader v-model="organizationUnitMoveInput.newParentId" :options="optionsOrganizationUnitsTransfer" :props="{ label: 'displayName', value: 'id' }" style="width: 90%;" clearable placeholder="请选择机构" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogTransferOrganization = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="submitLoading" @click="handleSubmitTransferOrganization">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
    <!-- 开启道馆 -->
    <el-dialog title="分配系统" width="440px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="optionGym">
      <el-form ref="gymForm" label-width="130px" :model="formgym" :rules="formgym_rules" @submit.native.prevent>
        <el-form-item label="选择道馆版本" prop="editionId" size="mini">
          <el-select v-model="formgym.editionId" style="width: 100%" placeholder="选择道馆版本">
            <el-option v-for="(item, index) in showEditionList" :key="index" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" size="mini" prop="phoneNumber">
          <el-input v-model="formgym.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="optionGym = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="submitLoading" @click="handleSubmitOpenClub">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserToken, getLocalToken, getTenantId } from '@/lib/auth';
import { apiappClubtAManagementclubSetting } from './club.js';
import {
  api_GET_MallStoreCurrent
} from '@/extend/api/shoppingmallswaggerApi/app.js';
import { api_GET_ClubTAManagementDelegationOrganizationUnitId } from '@/extend/api/hallswaggerApi/app.js';
import Teampeople from './teampeople/teamlist.vue';
import { translateByCode } from '@/lib/getTransData';
import { CopyData, deepCopy } from '@/lib/index';
import Sticky from '@/components/Sticky';
import ClubBaseInfo from './components/ClubBaseInfo';
import {
  FormAddUnitVO_Rules,
  FormAddUserVo_Rules,
  OrganizationUnitMoveInput_Rules,
  UpdateOrganizationUnitEditionInput_Rules
} from '@/lib/validate/identity';
import {
  Api_GET_OrganizationUnitsIdUsersQO,
  OrganizationUnitCreateInput,
  Api_GET_OrganizationUnitsTreeIdQO,
  IdentityUserCreateDto, // 新增/修改
  OrganizationUnitMoveInput,
  UpdateOrganizationUnitEditionInput
} from '@/lib/form/swaggerForm';
import {
  api_GET_OrganizationUnitsCanCreateRoot, // 是否允许添加顶级组织机构
  api_POST_OrganizationUnits, // 新建组织机构
  api_DELETE_OrganizationUnitsId, // 删除组织结构
  api_PUT_OrganizationUnitsId, // 修改组织结构
  api_GET_OrganizationUnitsTree, // 获取组织结构树结构
  api_GET_RolesDefault, // 获取通用角色列表
  api_GET_RolesAll, // 获取角色列表
  api_GET_OrganizationUnitsIdUsers, // 获取用户列表
  api_POST_Users, // 新增用户
  api_DELETE_UsersId, // 删除用户
  api_PUT_UsersId, // 修改用户
  api_PUT_UsersIdChangeOrganizationUnit, // 修改用户分组 = 转组
  api_PUT_UsersIdDisable, // 禁用用户
  api_PUT_UsersIdEnable, // 启用用户
  api_GET_OrganizationUnitsTypes, // 获取组织架构列表
  api_PUT_OrganizationUnitsIdEnable, // 启用组织架构
  api_PUT_OrganizationUnitsIdDisable, // 禁用组织架构
  api_PUT_OrganizationUnitsIdMove,
  api_GET_UsersIdRoles,
  api_GET_OrganizationUnitsList, // 获取组织机构列表（有读取权限的）
  // api_GET_UsersPemissionOrganizationUnits, // 获取组织机构列表
  api_GET_OrganizationUnitsIdChildren, // 获取下级组织机构列表（直接下级）
  api_GET_OrganizationUnitsTreeId, // 获取指定组织机构树
  api_GET_Edition, // 查询版本列表
  api_POST_EditionOuEdition // 更新机构的版本
} from '@/extend/api/swaggerApi/identity';
import {
  api_GET_Provinces,
  api_GET_CitiesProvinceCode,
  api_GET_CountiesCityCode
} from '@/extend/api/swaggerApi/district';
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import { errorText } from '@/lib';
import { mapState } from 'vuex';

export default {
  name: 'Organization',
  components: {
    Sticky,
    ClubBaseInfo,
    Teampeople
  },
  data() {
    return {
      organizationUnitId: '',
      department: true,
      infoCity: {
        provinceCode: '',
        cityCode: '',
        countyCode: ''
      },
      duanzong: false,
      jumpPathHall: '',
      jumpPath: '',
      storeId: '', // 商城id
      logo: '',
      DelegationId: '', // 机构id
      game: false,
      tran: false,
      mall: false,
      duan: false,
      TAManagement: false,
      // 赛事，培训，商城权限, 级段位
      headerTop: {},
      activeName: 0,
      canCreateRoot: null,
      orgPageListQO: new Api_GET_OrganizationUnitsIdUsersQO(),
      organizationUnitCreateInput: new OrganizationUnitCreateInput(),
      organizationUnitsTreeIdQO: new Api_GET_OrganizationUnitsTreeIdQO(),
      identityUserCreateDto: new IdentityUserCreateDto(),
      totalPage: 0,
      currentPage: 1,
      organizationUnitsTree: [],
      // 树结构是否存在, 值为第一级的信息
      firstLevelInfo: {
        displayName: '',
        code: '',
        id: ''
      },
      currentTreeData: {},
      tableData: [],
      parentAddUnitInfo: {
        displayName: '',
        code: '',
        id: ''
      },
      currentAddUnitData: {
        id: '',
        code: '',
        displayName: ''
      },
      // 4种类型 addOrg: 新增组织(第一级); addTopLevel: 新增顶级单位; addSubBranch: 新增下属部门; editInfo: 修改信息
      dialogAddUnitInfo: {
        id: '',
        code: '',
        displayName: ''
      },
      optionGym: false, // 道馆弹窗
      isDefaultPwd: false, // 定义前端页面的一个控制，表单提交没有这个字段
      dialogOperateUnit: false,
      dialogOperateUnitType: '',
      formOperateUnitVO_Rules: new FormAddUnitVO_Rules(),
      dialogOperateUser: false,
      dialogOperateUserType: '',
      pwdIsDisabled: false,
      formOperateUserVo_Rules: new FormAddUserVo_Rules(),
      roleList: [],
      dialogTransfer: false,
      tableRow: {},
      formTransferVO: {
        sector: []
      },
      formTransferVO_Rules: {
        sector: [
          {
            type: 'array',
            required: true,
            message: '请选择一个部门',
            trigger: 'blur'
          }
        ]
      },
      cascaderKey: 0, // 解决级联选择器的重置问题
      optionsOrganizationUnits: [],
      treeLoading: false,
      loading: false,
      submitLoading: false,
      dialogLoading: false,
      randomPwd: '',
      // 组织架构列表
      organizationUnitsTypes: [],
      provinceList: [],
      cityList: [],
      countryList: [],
      // 当前选中的根type
      currentRootTypeCode: '',
      /* 机构转移相关 */
      dialogTransferOrganization: false,
      organizationUnitMoveInput: new OrganizationUnitMoveInput(),
      organizationUnitMoveInput_Rules: new OrganizationUnitMoveInput_Rules(),
      optionsOrganizationUnitsTransfer: [],
      buLoading: false,
      /* 道馆开启相关 */
      formgym: new UpdateOrganizationUnitEditionInput(),
      formgym_rules: new UpdateOrganizationUnitEditionInput_Rules(),
      editionList: [] // 版本列表
    };
  },
  computed: {
    ...mapState({
      info: state => state.user.info,
      tenantId: state => state.user.tenantId,
      userInfo: state => state.user.info,
      appTitle: state => state.app.title, // 标题
      roles: state => state.user.roles, // 标题
      typeCode: state => state.user.info.currentOrganizationUnit.typeCode, // 标题
      mallID: state => state.user.info.currentOrganizationUnit.id // 道馆id
    }),
    showEditionList () {
      // 启用 && 未删除
      return this.editionList.filter(item => item.isEnabled && !item.isDeleted);
    },
    currentTreeIsClub () {
      return this.currentTreeData.typeCode === 'Club';
    }
  },
  watch: {
    activeName(val) {
      if (val === '1') {
        this.$refs.teampeople.getMemberList();
      }
      // if (val === '0') {
      //   this.orgPageListQO = new Api_GET_OrganizationUnitsIdUsersQO();
      //   this.orgPageListQO.IsEnabled = '';
      //   this.getPageData();
      // }
    },
    dialogOperateUnit(val) {
      if (!val) {
        this.parentAddUnitInfo = {
          displayName: '',
          code: '',
          id: ''
        };
        this.currentAddUnitData = {
          id: '',
          code: '',
          displayName: ''
        };
        this.organizationUnitCreateInput = new OrganizationUnitCreateInput();
        this.$refs['refFormAddUnit'].resetFields();
      }
    },
    dialogOperateUser(val) {
      if (!val) {
        // 关闭
        this.$refs['refFormAddUser'].resetFields();
      } else {
        this.isDefaultPwd = false; // 新增/编辑时置为false，避免连续添加回显问题
        if (this.dialogOperateUserType === 'add') {
          this.identityUserCreateDto = new IdentityUserCreateDto();
          this.identityUserCreateDto.isEnabled = true;
        }
        this.randomPwd = '';
        if (this.dialogOperateUserType === 'edit') {
          this.identityUserCreateDto.isEnabled = this.tableRow.isEnabled;
          // 编辑时默认回显一个随机生成的密码
          this.randomPwd = `Yd#&*_${Math.floor(
            (Math.random() + Math.floor(Math.random() * 9 + 1)) *
              Math.pow(10, 10 - 1)
          )}`;
          this.identityUserCreateDto.password = this.randomPwd; // 随机
        }
      }
    },
    dialogTransfer(val) {
      if (!val) {
        this.$refs['refFormTransfer'].resetFields();
        this.formTransferVO.sector = [];
      }
    },
    isDefaultPwd(val) {
      if (val) {
        this.identityUserCreateDto.password = 'Asd123';
      } else {
        // 编辑 生成随机密码
        if (this.dialogOperateUserType === 'edit') {
          this.randomPwd = `Yd#&*_${Math.floor(
            (Math.random() + Math.floor(Math.random() * 9 + 1)) *
              Math.pow(10, 10 - 1)
          )}`;
          this.identityUserCreateDto.password = this.randomPwd; // 随机
        }
        // 新增 为空
        if (this.dialogOperateUserType === 'add') {
          this.identityUserCreateDto.password = '';
        }
      }
      this.pwdIsDisabled = val;
    }
  },
  created() {
    this.init();
    api_GET_OrganizationUnitsCanCreateRoot().then(res => {
      this.canCreateRoot = res;
    });
    this.orgPageListQO.IsEnabled = '';
    this.getOrganizationUnitsTree();
    this.getOrganizationUnitsTypes();
    this.getProvinceList();
    this.getEditionList({
      IncludeValidityType: true
    });
    this.roles.map(res => {
      if (res === 'GameManageIdenty') {
        this.game = true;
      }
      if (res === 'Training') {
        this.tran = true;
      }
      if (res === 'Mall') {
        this.mall = true;
      }
      if (res === 'TAManagement') {
        this.TAManagement = true;
      }
      if (res === 'DuanSetting') {
        if (this.typeCode !== 'WXCenter') {
          if (!this.duanzong) {
            this.duan = true;
          }
        }
      }
    });
    if (this.TAManagement === true) {
      this.getLogo(this.userInfo.currentOrganizationUnit.id);
    }

    console.log(this.game, this.mall, this.tran);
  },
  methods: {
    init() {
      if (this.info) {
        this.duanzong = Boolean(this.info.currentOrganizationUnit.cityCode);
      }
    },
    // 重置
    handleRefreshData() {
      this.orgPageListQO = new Api_GET_OrganizationUnitsIdUsersQO();
      this.orgPageListQO.IsEnabled = '';
      this.getPageData();
    },
    // 获取组织架构类型列表
    getOrganizationUnitsTypes() {
      return new Promise((resolve, reject) => {
        api_GET_OrganizationUnitsTypes().then(
          res => {
            console.log(res);
            this.organizationUnitsTypes = res.items || [];
            resolve(res.items);
          },
          error => reject(error)
        );
      });
    },
    // 获取树结构数据
    getOrganizationUnitsTree() {
      this.treeLoading = true;
      api_GET_OrganizationUnitsList()
        .then(res => {
          this.organizationUnitsTree = res.items;
          console.log(this.organizationUnitsTree);
          if (this.organizationUnitsTree.length > 0) {
            // 树结构有数据时表格默认按第一级获取对应数据
            CopyData(this.organizationUnitsTree[0], this.firstLevelInfo);
            this.currentRootTypeCode = res.items[0].typeCode;
            this.$nextTick(function() {
              this.$refs.viewTree &&
                this.$refs.viewTree.setCurrentKey(
                  this.organizationUnitsTree[0].code
                );
            });
            this.handleNodeClick(this.organizationUnitsTree[0]);
          } else {
            // 显示新增组织, 新增第一级
            this.firstLevelInfo = {
              displayName: '',
              code: '',
              id: ''
            };
          }
          this.treeLoading = false;
        })
        .catch(() => {
          this.treeLoading = false;
        });
    },
    loadTreeNode(node, resolve) {
      if (node.level === 0) {
        this.organizationUnitsTree[0].children = null;
        return resolve(this.organizationUnitsTree);
      }
      if (node.level >= 1) {
        api_GET_OrganizationUnitsIdChildren(node.data.id, {
          includeDetails: true
        }).then(
          res => {
            const _list = (res && res.items) || [];
            _list.sort((a, b) => {
              const _a = a.creationTime;
              const _b = b.creationTime;
              if (_a < _b) { return -1; }
              if (_a > _b) { return 1; }
              return 0;
            });
            this.filterTreeTypeCodeIsClub(_list);
            resolve(_list);
          },
          error => {
            this.$message({
              type: 'error',
              message: (error.error && error.error.message) || ''
            });
            resolve([]);
          }
        );
      }
    },
    filterTreeTypeCodeIsClub (data) {
      // 因业务调整，如果树节点是club,则不能展开获取下一级。所以在此过滤一下
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        if (item.typeCode === 'Club') {
          item._ISLEAF = true;
        }
      }
    },
    // 树结构节点被点击时的回调
    handleNodeClick(data, node) {
      // data.parentId 不存在代表是第一级
      if (data && data.parentId && node) {
        this.parentAddUnitInfo = node.parent.data;
      } else {
        this.parentAddUnitInfo = {
          displayName: '',
          code: '',
          id: ''
        };
      }
      this.currentTreeData = data;
      console.log(data);
      this.organizationUnitId = data.id;
      if (data.typeCode === 'Club') {
        this.getteamname(data.id);
      }
      if (data.typeCode === null) {
        this.department = false;
      } else {
        this.department = true;
      }
      this.infoCity.provinceCode = data.provinceCode;
      this.infoCity.cityCode = data.cityCode;
      this.infoCity.countyCode = data.countyCode;
      if (this.TAManagement === true) {
        if (data.typeCode !== 'Club') {
          if (data.typeCode !== null) {
            this.getLogo(data.id);
          } else {
            this.getLogo(data.parentId);
          }
        }
      }

      if (data.typeCode !== 'Club') {
      // 因业务调整，无法查看道馆下的人员数据，同时也无法操作，所以目前道馆相关的展示页面作出调整。无需执行getPageData

        this.getPageData();
      } else {
        this.tableData = [];
      }
      // } else {
      //   this.activeName = '1';
      // }
    },
    getteamname(id) {
      apiappClubtAManagementclubSetting(id).then(res => {
        if (res) {
          console.log(res, 'sssssssssss');
        }
      }).catch(
        error => {
          console.error(erro);
          this.$message({
            message: `获取失败 ${error.error.message}`,
            type: 'error',
            showClose: true
          });
        }
      );
      api_GET_ClubTAManagementDelegationOrganizationUnitId(id).then(res => {
        this.logo = res.imagePath;
        if (res) {
          this.$set(this.currentTreeData, 'address', this.parentAddUnitInfo.displayName);
          this.$set(this.currentTreeData, 'teamname', res.name);
          this.$set(this.currentTreeData, 'teamprovinceCode', res.provinceCode);
          this.$set(this.currentTreeData, 'teamcityCode', res.cityCode);
          this.$set(this.currentTreeData, 'teamcountyCode', res.countyCode);
        } else {
          this.$refs.teampeople.tableData = [];
        }
      }).catch(
        error => {
          console.error(erro);
          this.$message({
            message: `获取失败 ${error.error.message}`,
            type: 'error',
            showClose: true
          });
        }
      );
    },
    // 获取树点击机构logo
    getLogo(id) {
      api_GET_ClubTAManagementDelegationOrganizationUnitId(id).then(res => {
        this.logo = res.imagePath;
        if (res) {
          this.$refs.teampeople.delegationId = res.id;
          this.$refs.teampeople.getMemberList();
        } else {
          this.$refs.teampeople.tableData = [];
        }
      }).catch(
        error => {
          console.error(erro);
          this.$message({
            message: `获取失败 ${error.error.message}`,
            type: 'error',
            showClose: true
          });
        }
      );
    },
    // 获取表格数据
    getPageData(page) {
      this.loading = true;
      this.orgPageListQO.Page = page || 1;
      this.orgPageListQO.SkipCount =
        (this.orgPageListQO.Page - 1) * this.orgPageListQO.MaxResultCount;
      api_GET_OrganizationUnitsIdUsers(
        this.currentTreeData.id,
        this.orgPageListQO
      ).then(
        res => {
          this.tableData = res.items;
          this.totalPage = res.totalCount;
          this.loading = false;
        },
        error => {
          this.$message({
            type: 'error',
            message: (error.error && error.error.message) || ''
          });
          this.loading = false;
        }
      );
    },
    sizeChange(MaxResultCount) {
      this.orgPageListQO.MaxResultCount = MaxResultCount;
      this.getPageData();
    },
    pageIndexChange(currentPage) {
      this.getPageData(currentPage);
    },
    // 为 Table 中的某一行添加 class
    tableRowClassName({ row, rowIndex }) {
      if (!row.isEnabled) {
        return 'gl_color_grey';
      }
      return '';
    },
    // 弹框 —— 新增/编辑下属部门
    dropdownAddUnitDialog(data, type) {
      this.dialogOperateUnitType = data.type || '';
      this.cityList = [];
      this.countryList = [];
      if (data === 'addSibling') {
        // data = addSibling 表示新增与第一级同级的组织, 但实际该组织还是隶属于第一级
        this.dialogOperateUnitType = 'add';
        this.dialogAddUnitInfo = {
          displayName: type === 'addTopLevel' ? '新增顶级单位' : '新增组织',
          code: type
        };
        this.dialogOperateUnit = true;
      } else {
        this.parentAddUnitInfo = data.node.parent.data;
        this.currentAddUnitData = data.tree;
        this.organizationUnitCreateInput = new OrganizationUnitCreateInput();
        // 删除
        if (data.type === 'delete') {
          this.dropdownDeleteUnit(data.node, data.tree);
        }
        // 新增下属部门
        if (data.type === 'add') {
          this.dialogAddUnitInfo = {
            displayName: '新增下属部门',
            code: 'addSubBranch'
          };
          this.dialogOperateUnit = true;
        }
        // 编辑 - 部门
        if (data.type === 'edit') {
          this.dialogAddUnitInfo = {
            displayName: '修改信息',
            code: 'editInfo'
          };
          CopyData(this.currentAddUnitData, this.organizationUnitCreateInput);
          this.dialogOperateUnit = true;
        }
        // 新增内部机构
        if (data.type === 'addInner') {
          this.dialogAddUnitInfo = {
            displayName: '新增内部机构',
            code: 'addSubBranch',
            typeCode: data.tree.typeCode
          };
          if (this.dialogAddUnitInfo.typeCode === 'ProvinceTA') {
            this.organizationUnitCreateInput.typeCode = 'CityTA';
          }
          if (this.dialogAddUnitInfo.typeCode === 'CityTA') {
            this.organizationUnitCreateInput.typeCode = 'CountyTA';
          }
          this.dialogOperateUnit = true;
        }
        // 编辑 - 内部机构
        if (data.type === 'editInner') {
          this.dialogAddUnitInfo = {
            displayName: '修改信息',
            code: 'editInfo',
            typeCode: data.tree.typeCode
          };
          CopyData(this.currentAddUnitData, this.organizationUnitCreateInput);
          console.log(this.organizationUnitCreateInput);
          this.getCityList(this.organizationUnitCreateInput.provinceCode);
          this.getCountryList(this.organizationUnitCreateInput.cityCode);
          this.dialogOperateUnit = true;
        }
        // 启用
        if (data.type === 'enabled') {
          this.handleEnableDelegation(data.node, data.tree);
        }
        // 禁用
        if (data.type === 'disabled') {
          this.$confirm(
            `您确定要禁用 [${data.tree.displayName}] 吗？禁用后该机构下属账号将无法登陆！`,
            '提示',
            {
              confirmButtonText: translateByCode('alert.confirm'),
              cancelButtonText: translateByCode('alert.cancel'),
              type: 'warning'
            }
          ).then(() => {
            this.handledDisableDelegation(data.node, data.tree);
          });
        }
        // 转移
        if (data.type === 'transfer') {
          this.organizationUnitMoveInput = new OrganizationUnitMoveInput();
          api_GET_OrganizationUnitsTreeId(
            this.$store.state.user.currentUserType.organizationUnitId
          ).then(
            res => {
              console.log(res);
              if (res) {
                this.optionsOrganizationUnitsTransfer = this.handleOrganizationUnitsTransfer(
                  deepCopy(Array.isArray(res) ? res : [res])
                );
              }
            },
            error => {
              console.error(error);
            }
          );
          this.dialogTransferOrganization = true;
        }
        // 开启道馆
        if (data.type === 'addgym') {
          const _vo = new UpdateOrganizationUnitEditionInput();
          _vo.organizationUnitId = data.tree.id;
          this.formgym = _vo;
          this.optionGym = true;
          this.$nextTick(() => {
            this.$refs.gymForm.resetFields();
          });
        }
      }
    },
    // 处理转组时候的机构树
    handleOrganizationUnitsTransfer(organizationUnitsTree) {
      const optionsOrganizationUnitsTransfer = [];
      for (let i = 0; i < organizationUnitsTree.length; i++) {
        const item = organizationUnitsTree[i];
        if (
          item.typeCode === 'ProvinceTA' ||
          item.typeCode === 'CityTA' ||
          item.typeCode === 'WXCenter' ||
          item.typeCode === 'CountyTA'
        ) {
          if (item.children) {
            item.children = this.handleOrganizationUnitsTransfer(item.children);
          }
          item.children =
            item.children && item.children.length ? item.children : null;
          optionsOrganizationUnitsTransfer.push(item);
        }
      }
      return optionsOrganizationUnitsTransfer;
    },
    handleSubmitTransferOrganization() {
      this.$refs['organizationUnitMoveInput'].validate(valid => {
        if (!valid) return;
        const query = {
          newParentId: this.organizationUnitMoveInput.newParentId.slice(-1)[0]
        };
        this.submitLoading = true;
        api_PUT_OrganizationUnitsIdMove(this.currentAddUnitData.id, query).then(
          res => {
            this.submitLoading = false;
            this.$message({ type: 'success', message: '操作成功！' });
            this.getOrganizationUnitsTree();
            this.dialogTransferOrganization = false;
          },
          error => {
            this.submitLoading = false;
            this.$message({
              type: 'error',
              message: (error.error && error.error.message) || ''
            });
          }
        );
      });
    },
    handleSubmitOpenClub () {
      this.$refs.gymForm.validate(
        valid => {
          if (valid) {
            this.apiUpdateOUEdition(this.formgym);
          }
        }
      );
    },
    apiUpdateOUEdition (_vo) {
      this.submitLoading = true;
      api_POST_EditionOuEdition(_vo)
        .then(
          res => {
            this.submitLoading = false;
            this.optionGym = false;
            console.log('res: ', res);
            if (_vo.organizationUnitId === this.currentTreeData.id) {
              this.$refs.refClubBaseInfo.reGetClubEditionById();
            }
            this.$message({
              message: `操作成功`,
              type: 'success',
              showClose: true
            });
          }
        )
        .catch(
          error => {
            this.submitLoading = false;
            this.$message({
              message: `操作失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 获取道馆版本列表
    getEditionList (_qo) {
      api_GET_Edition(_qo)
        .then(
          res => {
            this.editionList = res || [];
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            console.log(error);
          }
        );
    },
    // 启用组织机构
    handleEnableDelegation(node, data) {
      return new Promise((resolve, reject) => {
        api_PUT_OrganizationUnitsIdEnable(data.id).then(
          res => {
            this.getOrganizationUnitsTree();
            this.$message({ type: 'success', message: '操作成功！' });
            resolve(res);
          },
          error => {
            this.$message({
              type: 'error',
              message: (error.error && error.error.message) || ''
            });
            reject(error);
          }
        );
      });
    },
    // 禁用组织机构
    handledDisableDelegation(node, data) {
      return new Promise((resolve, reject) => {
        console.log(data);
        api_PUT_OrganizationUnitsIdDisable(data.id).then(
          res => {
            this.getOrganizationUnitsTree();
            this.$message({ type: 'success', message: '操作成功！' });
            resolve(res);
          },
          error => {
            this.$message({
              type: 'error',
              message: (error.error && error.error.message) || ''
            });
            reject(error);
          }
        );
      });
    },
    // 提交 —— 新增/编辑下属部门
    dropdownSubmitUnit() {
      this.$refs['refFormAddUnit'].validate(valid => {
        if (valid) {
          this.submitLoading = true;
          if (
            this.dialogOperateUnitType === 'add' ||
            this.dialogOperateUnitType === 'addInner'
          ) {
            if (this.dialogAddUnitInfo.code === 'addSubBranch') {
              // addSubBranch: 新增下属部门 需带parentId
              this.organizationUnitCreateInput.parentId = this.currentAddUnitData.id;
            } else {
              // addOrg: 新增组织(第一级); addTopLevel: 新增顶级单位 这两个不需要带parentId
              this.organizationUnitCreateInput.parentId = '';
            }
            this.organizationUnitCreateInput.typeCode =
              this.organizationUnitCreateInput.typeCode || null;
            this.organizationUnitCreateInput.includeDetails = false; // 该参数暂时默认设置为false
            this.organizationUnitCreateInput.isExternal = false; // 该参数暂时默认设置为false
            api_POST_OrganizationUnits(this.organizationUnitCreateInput).then(
              res => {
                this.submitLoading = false;
                this.dialogOperateUnit = false;
                this.getOrganizationUnitsTree();
                this.$message({ type: 'success', message: '操作成功！' });
              },
              error => {
                this.submitLoading = false;
                this.$message({
                  type: 'error',
                  message: (error.error && error.error.message) || ''
                });
              }
            );
          }
          if (
            this.dialogOperateUnitType === 'edit' ||
            this.dialogOperateUnitType === 'editInner'
          ) {
            this.organizationUnitCreateInput.includeDetails = false; // 该参数暂时默认设置为false
            api_PUT_OrganizationUnitsId(
              this.currentAddUnitData.id,
              this.organizationUnitCreateInput
            ).then(
              res => {
                this.submitLoading = false;
                this.dialogOperateUnit = false;
                this.getOrganizationUnitsTree();
                this.$message({ type: 'success', message: '操作成功！' });
              },
              error => {
                this.submitLoading = false;
                this.$message({
                  type: 'error',
                  message: (error.error && error.error.message) || ''
                });
              }
            );
          }
        } else {
          this.submitLoading = false;
          return false;
        }
      });
    },
    // 删除 —— 删除下属部门
    dropdownDeleteUnit(node, data) {
      this.$confirm(`您确定要删除 [${data.displayName}] 吗？`, '提示', {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        api_DELETE_OrganizationUnitsId(data.id).then(
          res => {
            this.getOrganizationUnitsTree();
            this.$message({ type: 'success', message: '操作成功！' });
          },
          error => {
            this.$message({
              type: 'error',
              message: (error.error && error.error.message) || ''
            });
          }
        );
      });
    },
    // 弹框 —— 新增/编辑用户
    handleOperateUserRow(type, row) {
      this.dialogLoading = true;
      this.identityUserCreateDto.roleIds = '';
      Promise.all([this.getDefaultRoles(), this.getRoleList()]).then(
        res => {
          console.log(res);
          let items = [];
          if (res[0]) {
            items = items.concat(res[0], res[1].items);
          } else {
            items = res[1].items || [];
          }
          this.roleList = items;
          this.dialogLoading = false;
        },
        () => {
          this.dialogLoading = false;
        }
      );
      this.tableRow = row;
      if (type === 'edit') {
        CopyData(row, this.identityUserCreateDto);
        api_GET_UsersIdRoles(row.id).then(
          res => {
            if (res.items && res.items.length > 0) {
              res.items.filter(item => {
                this.identityUserCreateDto.roleIds = item.id;
              });
            }
          },
          error => {
            this.submitLoading = false;
            this.$message({
              type: 'error',
              message: (error.error && error.error.message) || ''
            });
          }
        );
      }
      this.dialogOperateUserType = type;
      this.dialogOperateUser = true;
      this.$nextTick(() => {
        this.$refs.refFormAddUser && this.$refs.refFormAddUser.clearValidate();
      });
    },
    // 获取角色列表
    getRoleList() {
      return new Promise((resolve, reject) => {
        api_GET_RolesAll().then(
          res => {
            resolve(res);
          },
          error => {
            reject(error);
          }
        );
      });
    },
    // 获取通用角色列表
    getDefaultRoles() {
      return new Promise((resolve, reject) => {
        api_GET_RolesDefault({ searchParent: true }).then(
          res => {
            resolve(res);
          },
          error => {
            reject(error);
          }
        );
      });
    },
    // 提交 —— 新增/修改用户
    handleSubmitUser() {
      this.$refs['refFormAddUser'].validate(valid => {
        this.submitLoading = true;
        if (valid) {
          const _identityUserCreateDto = deepCopy(this.identityUserCreateDto);
          _identityUserCreateDto.roleNames = null; // roleNames的默认值如没有则必须传null，否则角色权限提交会失败
          // 处理角色身份
          _identityUserCreateDto.roleIds = [_identityUserCreateDto.roleIds];
          if (this.dialogOperateUserType === 'add') {
            _identityUserCreateDto.userName = null; // 默认不能为string
            _identityUserCreateDto.email = null; // 默认不能为string
            _identityUserCreateDto.organizationUnitId = this.currentTreeData.id; // 所属组织机构ID，必填
            api_POST_Users(_identityUserCreateDto).then(
              res => {
                this.submitLoading = false;
                this.dialogOperateUser = false;
                this.getPageData();
                this.$message({ type: 'success', message: '操作成功！' });
              },
              error => {
                this.submitLoading = false;
                this.$message({
                  type: 'error',
                  message: (error.error && error.error.message) || ''
                });
              }
            );
          }
          if (this.dialogOperateUserType === 'edit') {
            _identityUserCreateDto.concurrencyStamp = this.tableRow.concurrencyStamp; // 修改信息需带上concurrencyStamp
            if (this.identityUserCreateDto.password === this.randomPwd) {
              // 如果传入的密码===随机生成的密码，则传空代表使用原密码
              _identityUserCreateDto.password = '';
            }
            api_PUT_UsersId(this.tableRow.id, _identityUserCreateDto).then(
              res => {
                this.submitLoading = false;
                this.dialogOperateUser = false;
                this.getPageData(this.orgPageListQO.Page);
                this.$message({ type: 'success', message: '操作成功！' });
              },
              error => {
                this.submitLoading = false;
                this.$message({
                  type: 'error',
                  message: (error.error && error.error.message) || ''
                });
              }
            );
          }
        } else {
          this.submitLoading = false;
          return false;
        }
      });
    },
    // 用户禁用
    handleForbidden(row) {
      this.$confirm(`您确定要操作 [${row.name}] 吗？`, '提示', {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        if (row.isEnabled) {
          // 禁用用户
          api_PUT_UsersIdDisable(row.id).then(
            res => {
              this.getPageData(this.orgPageListQO.Page);
              this.$message({ type: 'success', message: '操作成功！' });
            },
            error => {
              this.$message({
                type: 'error',
                message: (error.error && error.error.message) || ''
              });
            }
          );
        } else {
          // 启用用户
          api_PUT_UsersIdEnable(row.id).then(
            res => {
              this.getPageData(this.orgPageListQO.Page);
              this.$message({ type: 'success', message: '操作成功！' });
            },
            error => {
              this.$message({
                type: 'error',
                message: (error.error && error.error.message) || ''
              });
            }
          );
        }
      });
    },
    // 弹框 —— 用户转组
    handleTransfer(row) {
      console.log(row);
      this.tableRow = row;
      api_GET_OrganizationUnitsTree().then(res => {
        console.log(res.items);
        this.optionsOrganizationUnits = this.processTreeData(res.items);
      });
      ++this.cascaderKey;
      this.dialogTransfer = true;
    },
    // 提交 —— 用户转组
    handleSubmitUserTransfer() {
      this.$refs['refFormTransfer'].validate(valid => {
        if (valid) {
          // organizationId默认获取级联的最后一个
          console.log(this.formTransferVO, this.tableRow);
          const query = {
            fromOrganizationUnitId: this.tableRow.organizationUnits[0].id,
            organizationUnitId: this.formTransferVO.sector[
              this.formTransferVO.sector.length - 1
            ]
          };
          api_PUT_UsersIdChangeOrganizationUnit(this.tableRow.id, query).then(
            res => {
              this.submitLoading = false;
              this.dialogTransfer = false;
              this.getPageData(this.orgPageListQO.Page);
              this.$message({ type: 'success', message: '操作成功！' });
            },
            error => {
              this.submitLoading = false;
              this.$message({
                type: 'error',
                message: (error.error && error.error.message) || ''
              });
            }
          );
        } else {
          this.submitLoading = false;
          return false;
        }
      });
    },
    // 用户删除
    handleDeleteUser(row) {
      this.$confirm(`您确定要删除 [${row.name}] 吗？`, '提示', {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        api_DELETE_UsersId(row.id).then(
          res => {
            this.getPageData();
            this.$message({ type: 'success', message: '操作成功！' });
          },
          error => {
            this.$message({
              type: 'error',
              message: (error.error && error.error.message) || ''
            });
          }
        );
      });
    },
    // 递归处理列表，把最后的children设为undefined
    processTreeData(data) {
      console.log(data);
      console.log(this.tableRow.organizationUnit);
      for (var i = 0; i < data.length; i++) {
        if (data[i].typeCode === 'Club') {
          data[i].disabled = true;
        }

        if (data[i].id === this.tableRow.organizationUnits[0].id) {
          data[i].disabled = true;
        }
        if (data[i].children.length < 1) {
          data[i].children = undefined;
        } else {
          this.processTreeData(data[i].children);
        }
      }
      return data;
    },
    // 获取省列表
    getProvinceList() {
      return new Promise((resolve, reject) => {
        api_GET_Provinces().then(
          res => {
            this.provinceList = res || [];
            resolve(res);
          },
          error => {
            reject(error);
          }
        );
      });
    },
    // 获取市列表
    getCityList(province) {
      if (!province) {
        this.cityList = [];
        return;
      }
      return new Promise((resolve, reject) => {
        api_GET_CitiesProvinceCode(province).then(
          res => {
            this.cityList = res || [];
            resolve(res);
          },
          error => {
            this.$message({
              type: 'error',
              message: (error.error && error.error.message) || ''
            });
            reject(error);
          }
        );
      });
    },
    // 获取县列表
    getCountryList(city) {
      if (!city) {
        this.countryList = [];
        return;
      }
      return new Promise((resolve, reject) => {
        api_GET_CountiesCityCode(city).then(
          res => {
            this.countryList = res || [];
            resolve(res);
          },
          error => {
            this.$message({
              type: 'error',
              message: (error.error && error.error.message) || ''
            });
            reject(error);
          }
        );
      });
    },
    findDictDataByCode(code) {
      return this.organizationUnitsTypes.find(item => item.code === code) || {};
    },
    // 数据导出
    reportData() {
      var that = this;
      this.buLoading = true;
      const tempUrl = `/api/excel`;
      const fileName = '数据导出' + '.xlsx';
      const params = {};
      params.ReportName = 'PlatformUser';
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, params)
        .then(res => {
          that.buLoading = false;
        })
        .catch(error => {
          that.buLoading = false;
          errorText(error).then(function(text) {
            that.$message({ type: 'error', message: text });
          });
        });
    },
    // 后期新增页面头部及团体成员
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return require('@/assets/images/face_default.png');
      }
    },
    // 跳转注册机构
    enrollorganization() {
      this.$router.push({ name: 'Enrollorganization', query: { infoCity: JSON.stringify(this.infoCity) }});
    },
    // 跳转注册人员
    toRegisterPersonal() {
      this.$router.push({ name: 'RegisterPersonal', query: { infoCity: JSON.stringify(this.infoCity) }});
    },
    // 跳转级段位
    toDanGrade() {
      if (this.userInfo.currentOrganizationUnit.typeCode === 'ProvinceTA') {
        const _origin = window.location.origin;
        const _pathname = window.location.pathname;
        const _orderUrl = `#/t__${this.tenantId || ''}/duan/maintenance`;
        const url = _origin + _pathname + _orderUrl;
        var a = document.createElement('a');
        var event = new MouseEvent('click');
        a.href = url;
        a.target = '_self';
        a.dispatchEvent(event);
      } else {
        let _token = this.$store.state.user.token || getLocalToken();
        if (!_token) {
          getUserToken().then(res => {
            _token = res;
            this.jumpPath = WEB_CONFIG.VUE_APP_CMS_URL + '?tokenid=' + _token;
          });
        } else {
          this.jumpPath = WEB_CONFIG.VUE_APP_CMS_URL + '?tokenid=' + _token;
        }
        this.jumpPathHall = '/hall.html#/t__' + (this.$store.state.user.tenantId || getTenantId() || '') + '/danGradeDeclare/declareManagement/';
        this.onclickSysChangeMenu();
      }
    },
    // 跳转会员费
    toMemberDues() {
      if (this.userInfo.currentOrganizationUnit.typeCode === 'ProvinceTA') {
        const _origin = window.location.origin;
        const _pathname = window.location.pathname;
        const _orderUrl = `#/t__${this.tenantId || ''}/membershipFee/paymentList`;
        const url = _origin + _pathname + _orderUrl;
        var a = document.createElement('a');
        var event = new MouseEvent('click');
        a.href = url;
        a.target = '_self';
        a.dispatchEvent(event);
      } else {
        let _token = this.$store.state.user.token || getLocalToken();
        if (!_token) {
          getUserToken().then(res => {
            _token = res;
            this.jumpPath = WEB_CONFIG.VUE_APP_CMS_URL + '?tokenid=' + _token;
          });
        } else {
          this.jumpPath = WEB_CONFIG.VUE_APP_CMS_URL + '?tokenid=' + _token;
        }
        this.jumpPathHall = '/hall.html#/t__' + (this.$store.state.user.tenantId || getTenantId() || '') + '/payMembership/payMembershiplist/';
        this.onclickSysChangeMenu();
      }
    },
    toOrganData() {
      this.$router.push({ name: 'OrganData', query: { organizationUnitId: this.organizationUnitId, disname: this.parentAddUnitInfo.displayName ? this.parentAddUnitInfo.displayName : '', currentTreeData: this.currentTreeData ? this.currentTreeData.displayName : '', Club: this.currentTreeData.typeCode }});
    },
    onclickSysChangeMenu (code) {
      this.jumpToSys(this.jumpPathHall);
    },
    jumpToSys (_href) {
      var a = document.createElement('a');
      var event = new MouseEvent('click');
      a.href = _href;
      a.target = '_blank';
      a.dispatchEvent(event);
    },
    // 跳转比赛
    goGame() {
      //       <span v-if="parentAddUnitInfo.id&&!currentTreeIsClub">{{ parentAddUnitInfo.displayName ? parentAddUnitInfo.displayName + ' -' : '' }}</span>
      // <span v-if="currentTreeData.id">{{ currentTreeData ? currentTreeData.displayName : '' }}</span>

      this.$router.push({ name: 'Gametap', query: { organizationUnitId: this.organizationUnitId, disname: this.parentAddUnitInfo.displayName ? this.parentAddUnitInfo.displayName : '', currentTreeData: this.currentTreeData ? this.currentTreeData.displayName : '' }});
      // const _origin = window.location.origin;
      // const _pathname = window.location.pathname;
      // const _orderUrl = `#/t__${this.tenantId || ''}/game/manage`;
      // const url = _origin + _pathname + _orderUrl;
      // var a = document.createElement('a');
      // var event = new MouseEvent('click');
      // a.href = url;
      // a.target = '_self';
      // a.dispatchEvent(event);
    },
    // 跳转培训
    goTran() {
      this.$router.push({ name: 'Train', query: { organizationUnitId: this.organizationUnitId, disname: this.parentAddUnitInfo.displayName ? this.parentAddUnitInfo.displayName : '', currentTreeData: this.currentTreeData ? this.currentTreeData.displayName : '' }});
      // const _origin = window.location.origin;
      // const _pathname = window.location.pathname;
      // const _orderUrl = `#/t__${this.tenantId || ''}/train/manage`;
      // const url = _origin + _pathname + _orderUrl;
      // var a = document.createElement('a');
      // var event = new MouseEvent('click');
      // a.href = url;
      // a.target = '_self';
      // a.dispatchEvent(event);
    },
    // 跳转商城
    goMall() {
      if (this.userInfo.currentOrganizationUnit.typeCode === 'Club') {
        this.api_GET_MallStoreCurrent();
      } else {
        this.$router.push({ name: 'Mall', query: { infoCity: JSON.stringify(this.infoCity), organizationUnitId: this.organizationUnitId }});
      }
    },
    // 获取当前用户店铺信息
    api_GET_MallStoreCurrent() {
      api_GET_MallStoreCurrent({ IncludeStatus: true }).then(res => {
        console.log(this.storeId);
        this.storeId = res.id || '';
        if (this.storeId === '') {
          this.$message({ type: 'warning', message: '未开通店铺' });
        } else {
          const _origin = window.location.origin;
          const _pathname = window.location.pathname;
          const _orderUrl = `#/t__${this.tenantId || ''}/mall/data`;
          const url = _origin + _pathname + _orderUrl;
          var a = document.createElement('a');
          var event = new MouseEvent('click');
          a.href = url;
          a.target = '_self';
          a.dispatchEvent(event);
        }
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    }
  }
};
</script>
<style scoped>
.el-dialog .el-dialog__body {
  height: 500px;
  overflow-y: scroll;
}
.view_tree .el-tree-node {
  white-space: normal;
}
.view_tree .el-tree-node__content {
  height: 100%;
  align-items: start;
}
.custom-tree-node {
  width: calc(100% - 24px);
  font-size: 14px;
  box-sizing: border-box;
}
.custom-tree-node .custom-tree-node-item {
  width: 30px;
  text-align: right;
  display: inline-block;
}
.headerTop {
  display: flex;
  align-items: center;
}
.img {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-left: 20px;
  margin-right: 12px;
}
</style>
<style>
.organization .el-scrollbar .el-scrollbar__wrap {
  overflow-x: hidden;
}
.organization .el-tree > .el-tree-node {
  width: 100%;
  display: inline-block;
}
.organization .el-dropdown {
  padding-right: 15px;
}
.tree_nodata {
  font-size: 12px;
  color: #909399;
  text-align: center;
}

</style>
